package com.xzb.demo.utils;

import org.apache.commons.lang3.StringUtils;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @author cuican
 * @version 2.0.0
 * @ClassName: CertUtil
 * @Description: sdk证书工具类，主要用于对证书的加载和使用
 */
public class CertUtil {

    public static final String PUBLIC_KEY = "public_key";
    public static final String PRIVATE_KEY = "private_key";


    private static Logger log = LoggerFactory.getLogger(CertUtil.class);


    private static final ConcurrentHashMap<String, Object> keys = new ConcurrentHashMap<String, Object>();

    public static void init(String publicKey, String privateKey) throws Exception {
        // 加载公钥
        initPulbicKey(publicKey);
        // 加载私钥
        initPrivateKey(privateKey);
    }

    public static PublicKey getPublicKey() {
        return (PublicKey) keys.get(PUBLIC_KEY);
    }

    public static PrivateKey getPrivateKey() {
        return (PrivateKey) keys.get(PRIVATE_KEY);
    }

    public static void initPulbicKey(String key) throws Exception {

        if (StringUtils.isNotEmpty(key)) {
            try {
                PublicKey publicKey = genPublicKey(key);
                keys.put(PUBLIC_KEY, publicKey);
            } catch (Exception e) {
                log.error("无法加载公钥[{}]", new Object[]{key});
                log.error(e.getMessage(), e);
                throw e;
            }
        }
    }

    public static void initPrivateKey(String key) throws Exception {
        try {
            PrivateKey privateKey = genPrivateKey(key);
            keys.put(PRIVATE_KEY, privateKey);
        } catch (Exception e) {
            log.error("无法加载私银[" + key + "]");
            log.error(e.getMessage(), e);
            throw e;
        }
    }


    /**
     * 得到私钥
     *
     * @param key 密钥字符串（经过base64编码）
     * @throws Exception
     */
    public static PrivateKey genPrivateKey(String key) throws Exception {

        byte[] keyBytes;

        keyBytes = Base64.decodeBase64(key);

        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");

        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

        return privateKey;
    }

    /**
     * 得到公钥
     *
     * @param key 密钥字符串（经过base64编码）
     * @throws Exception
     */
    public static PublicKey genPublicKey(String key) throws Exception {


        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] encodedKey = Base64.decodeBase64(key);
        PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));

        return publicKey;
    }

}
